//
//  simShopVisitCalendarController.m
//  simens
//
//  Created by amy zhang on 12-7-16.
//  Copyright (c) 2012年 yst. All rights reserved.
//

#import "simShopVisitCalendarController.h"
#import "simShopDetailController.h"
#import "TKCalendarMonthView.h"
#import "NSDateCategories.h"
#import "ASIHTTPRequest.h"
#import "MAWeekView.h"
#import "JSONKit.h"


#define DATE_COMPONENTS (NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)
#define CURRENT_CALENDAR [NSCalendar currentCalendar]


@implementation visitorItem

@synthesize custId,custName,custNumber,custStatus,contactName,contactPhone,visitNum,visitDate,datelineId,custNameEn,visitedNum;

@end


static int calendarShadowOffset = (int)-20;

@interface simShopVisitCalendarController () <TKCalendarMonthViewDelegate,MAWeekViewDelegate,TKCalendarMonthViewDataSource,UITableViewDelegate, UITableViewDataSource, ASIHTTPRequestDelegate,simShopDetailDelegate> {
	//TKCalendarMonthView *calendar;	
}

@property (nonatomic, retain) TKCalendarMonthView *calendar;
@property (strong) MAWeekView* weekcalendar;
@property (nonatomic,strong) UITableView *shopTableView;
@property (nonatomic,strong) UIImageView *bottomWeekImageView;
@property (nonatomic,strong) UIImageView *bottomMonthImageView;
@property (strong) NSMutableArray* weekButtonArray;
@property (strong) ASIHTTPRequest *request;
@property (nonatomic,strong) NSMutableArray* visitorItemArray;
@property (nonatomic,strong) NSMutableArray* todayVisitorItemArray;
@property (nonatomic,strong) NSArray* markArray;
@property (nonatomic,strong) NSString* dateStr;


- (void)toggleCalendar:(UIButton*) bt;

@end

@implementation simShopVisitCalendarController

@synthesize calendar = _calendar;
@synthesize shopTableView = _shopTableView;
@synthesize bottomWeekImageView=_bottomWeekImageView;
@synthesize bottomMonthImageView=_bottomMonthImageView;
@synthesize weekcalendar = _weekcalendar;
@synthesize selectDay = _selectDay;
@synthesize weekButtonArray = _weekButtonArray;
@synthesize request = _request;
@synthesize homePageDelegate = _homePageDelegate;
@synthesize visitorItemArray=_visitorItemArray;
@synthesize todayVisitorItemArray=_todayVisitorItemArray;
@synthesize markArray=_markArray;
@synthesize dateStr=_dateStr;



- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController.navigationBar setHidden:NO];
    
    self.title=@"计划拜访";
    
    //从服务器请求数据
    self.visitorItemArray = [[NSMutableArray alloc] init];
    self.todayVisitorItemArray=[[NSMutableArray alloc] init];
    
    
    self.calendar = [[TKCalendarMonthView alloc] init];
    self.calendar.delegate = self;
    self.calendar.dataSource = self;
    
    int statusBarHeight = 20;
	CGRect applicationFrame = (CGRect)[[UIScreen mainScreen] applicationFrame];
	self.view = [[UIView alloc] initWithFrame:CGRectMake(0, statusBarHeight, applicationFrame.size.width, applicationFrame.size.height)];
	self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	self.view.backgroundColor = [UIColor clearColor];
    
    
    UIBarButtonItem* tempRight = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewMessage)];
    self.navigationItem.rightBarButtonItem = tempRight;
    
    UIBarButtonItem* leftBt = [[UIBarButtonItem alloc] initWithTitle:@"切换周模式" style:UIBarButtonItemStylePlain target:self action:@selector(modeChangeButtonPress)];
    self.navigationItem.leftBarButtonItem = leftBt;
    
    
    self.shopTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                                       self.view.bounds.size.height) 
                                                      style:UITableViewStylePlain];  
    
    [self.shopTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.shopTableView setDelegate:self];
    [self.shopTableView setDataSource:self];
    self.shopTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview: self.shopTableView];

	
	// Add Calendar to just off the top of the screen so it can later slide down
	self.calendar.frame = CGRectMake(0, 0, self.calendar.frame.size.width, self.calendar.frame.size.height);
    [self.shopTableView setFrame:CGRectMake(0, 250, self.view.bounds.size.width,
                                            130)];
	// Ensure this is the last "addSubview" because the calendar must be the top most view layer
	[self.view addSubview:self.calendar];
	//[self.calendar reload];
    
    
    self.weekcalendar = [[MAWeekView alloc] init];
    [self.weekcalendar setFrame:CGRectMake(0, 0, 320, 115)];
    [self.weekcalendar setHidden:YES];
    [self.weekcalendar setDelegate:self];
    
    UIImageView* tempWeekHeadView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"weekhead.png"]];
    [tempWeekHeadView setFrame:CGRectMake(0, 33, 320, 14)];
    [self.weekcalendar addSubview:tempWeekHeadView];
   
    UIImageView* tempWeekBackView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"weekBack.png"]];
    [tempWeekBackView setFrame:CGRectMake(0, 47, 320, 65)];
    [self.weekcalendar addSubview:tempWeekBackView];
    
    NSArray* weekArray = [self.weekcalendar.weekdayView weekdays];
    
    int i = 0;
    
    if (self.weekButtonArray == nil) {
        self.weekButtonArray = [[NSMutableArray alloc] init];
    }
    else {
        [self.weekButtonArray removeAllObjects];
    }
    
    for (NSDate *date in weekArray) {
		NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];

        UIButton* tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [tempButton setFrame:CGRectMake(i*45.6, 48, 43, 59)];
        [tempButton setTitle:[NSString stringWithFormat:@"%i",[components day]] forState:UIControlStateNormal];
        [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFoc.png"] forState:UIControlStateHighlighted];

        [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFoc.png"] forState:UIControlStateSelected];

        [tempButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [tempButton setTag:i];
        
        [tempButton addTarget:self action:@selector(weekButtonSelected:) forControlEvents:UIControlEventTouchUpInside];

        i++;
        
        [self.weekButtonArray addObject:tempButton];
        [self.weekcalendar addSubview:tempButton];
    }    
    
    [self.view addSubview:self.weekcalendar];
    
    //初始化，月模式，显示日历
    [self toggleCalendar];
    
}


-(void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    
    //第一次进来加载
    
    if (self.request == nil) {
        [self updateFromHttp];        
    }
}

-(void) modeChangeButtonPress{
    
    //周模式
    if ([self.navigationItem.leftBarButtonItem.title isEqualToString:@"切换周模式"] == YES) {
        [self.navigationItem.leftBarButtonItem setTitle:@"切换月模式"];
        
        [self.calendar setHidden:YES];
        [self.weekcalendar setHidden:NO];
        
        //切换周时，参照月模式的选择日期
        if (self.calendar) {
            if (self.calendar.dateSelected) {                
                [self.weekcalendar setWeek:self.calendar.dateSelected];
            }
        }

        
        [self.shopTableView setFrame:CGRectMake(0, 100, self.view.bounds.size.width, 
                                                280)];

    //月模式    
    }else {
        [self.navigationItem.leftBarButtonItem setTitle:@"切换周模式"];
        
        [self.calendar setHidden:NO];
        [self.weekcalendar setHidden:YES];
        
        self.calendar.frame = CGRectMake(0, 0, self.calendar.frame.size.width, self.calendar.frame.size.height);
        [self.shopTableView setFrame:CGRectMake(0, 250, self.view.bounds.size.width, 130)]; 
             
        if (self.selectDay!=nil && ![self.selectDay isEqualToString:@""]) {
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            [self.calendar selectDate:[formatter dateFromString:self.selectDay]];
        }
    }
 
}

-(void) addNewMessage{
    if (self.dateStr == nil || [self.dateStr isEqualToString:@""]) {
        NSDate* date = [NSDate date];
        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        self.dateStr = [formatter stringFromDate:date];
    }

    if (_homePageDelegate) {
        [self.homePageDelegate changedToIndex:1];
    }
//    [shopVisitPlanController setPlanVistDate: dateStr];
//    [shopVisitPlanController setVistType: false];
//    [self.navigationController pushViewController:shopVisitPlanController animated:YES];
}

-(void) planVisit:(UIButton*) tbt{
    [self addNewMessage];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)toggleCalendar {
    
    if ([self.calendar isHidden] == YES) {
        return;
    }
    
    
	// If calendar is off the screen, show it, else hide it (both with animations)
	if (self.calendar.frame.origin.y == -self.calendar.frame.size.height+calendarShadowOffset) {
		// Show
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:.5];
		self.calendar.frame = CGRectMake(0, 0, self.calendar.frame.size.width, self.calendar.frame.size.height);
        [self.shopTableView setFrame:CGRectMake(0, 250, self.view.bounds.size.width, 
                                                130)];
        
		[UIView commitAnimations];
	} else {
		// Hide
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:.5];
		self.calendar.frame = CGRectMake(0, -self.calendar.frame.size.height+calendarShadowOffset, self.calendar.frame.size.width, self.calendar.frame.size.height);		
        [self.shopTableView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                self.view.bounds.size.height)];
        
		[UIView commitAnimations];
	}	
}

- (void)toggleCalendar:(UIButton*) bt {
	// If calendar is off the screen, show it, else hide it (both with animations)
	if (self.calendar.frame.origin.y == -self.calendar.frame.size.height+calendarShadowOffset) {
		// Show
        [bt setTitle:@"隐藏日历" forState:UIControlStateNormal];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:.75];
		self.calendar.frame = CGRectMake(0, 0, self.calendar.frame.size.width, self.calendar.frame.size.height);
        [self.shopTableView setFrame:CGRectMake(0, 250, self.view.bounds.size.width, 
                                                130)];

		[UIView commitAnimations];
	} else {
		// Hide
        [bt setTitle:@"显示日历" forState:UIControlStateNormal];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:.75];
		self.calendar.frame = CGRectMake(0, -self.calendar.frame.size.height+calendarShadowOffset, self.calendar.frame.size.width, self.calendar.frame.size.height);		
        [self.shopTableView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                                self.view.bounds.size.height)];

		[UIView commitAnimations];
	}	
}

#pragma mark -
#pragma mark TKCalendarMonthViewDelegate methods

- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
	NSLog(@"calendarMonthView didSelectDate");

    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"]; // 这里是用大写的 H
    self.dateStr = [dateFormatter stringFromDate:d];
    
    self.selectDay = self.dateStr;
    
    [self.todayVisitorItemArray removeAllObjects];
    
    for (visitorItem* item in self.visitorItemArray) {
        
        if ([item.visitDate isEqualToString: self.dateStr] == YES) {
            [self.todayVisitorItemArray addObject:item]; 
        }
    }
    
    [self.shopTableView reloadData];
}

- (void)calendarMonthView:(TKCalendarMonthView *)monthView monthDidChange:(NSDate *)d {
    
    self.selectDay=nil;
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-"];
    NSString* dateStr = [formatter stringFromDate:d];
    
    NSString* startDate = [NSString stringWithFormat:@"%@01",dateStr];
    NSString* endDate = [NSString stringWithFormat:@"%@31",dateStr];
    
    [self updateFromHttp: startDate endDate: endDate];
    
    
	NSLog(@"calendarMonthView monthDidChange");	
}

#pragma mark -
#pragma mark TKCalendarMonthViewDataSource methods

- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate {	
	NSLog(@"calendarMonthView marksFromDate toDate");	
	NSLog(@"Make sure to update 'data' variable to pull from CoreData, website, User Defaults, or some other source.");
	// When testing initially you will have to update the dates in this array so they are visible at the
	// time frame you are testing the code.
	//NSArray *data = [NSArray arrayWithObjects:
	//				 @"2012-07-16 00:00:00 +0000", @"2012-07-17 00:00:00 +0000", 
      //               @"2012-07-22 00:00:00 +0000", nil]; 
	
    
	// Initialise empty marks array, this will be populated with TRUE/FALSE in order for each day a marker should be placed on.
	NSMutableArray *marks = [NSMutableArray array];
	
	// Initialise calendar to current type and set the timezone to never have daylight saving
	NSCalendar *cal = [NSCalendar currentCalendar];
	[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
	
	// Construct DateComponents based on startDate so the iterating date can be created.
	// Its massively important to do this assigning via the NSCalendar and NSDateComponents because of daylight saving has been removed 
	// with the timezone that was set above. If you just used "startDate" directly (ie, NSDate *date = startDate;) as the first 
	// iterating date then times would go up and down based on daylight savings.
	NSDateComponents *comp = [cal components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit | 
                                              NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) 
                                    fromDate:startDate];
	NSDate *d = [cal dateFromComponents:comp];
	
	// Init offset components to increment days in the loop by one each time
	NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
	[offsetComponents setDay:1];	
	
    
	// for each date between start date and end date check if they exist in the data array
	while (YES) {
		// Is the date beyond the last date? If so, exit the loop.
		// NSOrderedDescending = the left value is greater than the right
		if ([d compare:lastDate] == NSOrderedDescending) {
			break;
		}
		
		// If the date is in the data array, add it to the marks array, else don't
		if ([self.markArray containsObject:[d description]]) {
			[marks addObject:[NSNumber numberWithBool:YES]];
		} else {
			[marks addObject:[NSNumber numberWithBool:NO]];
		}
		
		// Increment day using offset components (ie, 1 day in this instance)
		d = [cal dateByAddingComponents:offsetComponents toDate:d options:0];
	}
	
	//[offsetComponents release];
	
	return [NSArray arrayWithArray:marks];
}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}// Default is 1 if not implemented


//tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
   
        return [self.todayVisitorItemArray count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString* CellIdentifier = [NSString stringWithFormat:@"%d%d",indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    } 
    
    for (UIView *v in [cell subviews]) {
        if ([v isKindOfClass:[UILabel class]]|
            [v isKindOfClass:[UIImageView class]]) {
            [v removeFromSuperview];
        }
    }
    
      
        [cell.textLabel setBackgroundColor:[UIColor clearColor]];
        
        visitorItem* visitor = [self.todayVisitorItemArray objectAtIndex:indexPath.row];
        
//        NSString* laberStr = [NSString stringWithFormat:@"%d: %@前来拜访！", indexPath.row+1, visitor.custName];
//        [cell.textLabel setText:laberStr]; 
//        cell.textLabel.font=[UIFont systemFontOfSize:18];
//    
    
    if(visitor.visitNum.integerValue>visitor.visitedNum.integerValue){
        UIImage* img = [UIImage imageNamed:@"red.png"];    
        UIImageView *imageView =[[UIImageView alloc] initWithImage:img];
        [imageView setFrame:CGRectMake(3, 30, 20, 20)];
        [cell addSubview:imageView];
    }else{
        UIImage* img = [UIImage imageNamed:@"green.png"];    
        UIImageView *imageView =[[UIImageView alloc] initWithImage:img];
        [imageView setFrame:CGRectMake(0, 30, 25, 20)];
        [cell addSubview:imageView];
    }
   
    
    UILabel* shopnameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 180, 80)];
    [shopnameLabel setBackgroundColor:[UIColor clearColor]];
    [shopnameLabel setText:visitor.custNameEn]; 
    shopnameLabel.font=[UIFont systemFontOfSize:16];
    shopnameLabel.numberOfLines=3;
    [cell addSubview:shopnameLabel];
    
    UILabel* visitNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 5, 100, 20)];
    [visitNumLabel setBackgroundColor:[UIColor clearColor]];
    [visitNumLabel setText:[NSString stringWithFormat:@"计划拜访次数：%@",visitor.visitNum]];
    [visitNumLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitNumLabel.font=[UIFont systemFontOfSize:12];
    [cell addSubview:visitNumLabel];
    
    UILabel* visitedNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 25, 100, 20)];
    [visitedNumLabel setBackgroundColor:[UIColor clearColor]];
    [visitedNumLabel setText:[NSString stringWithFormat:@"已经拜访次数：%@",visitor.visitedNum]];
    [visitedNumLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitedNumLabel.font=[UIFont systemFontOfSize:12];
    [cell addSubview:visitedNumLabel];
    
    UILabel* visitdateLabel = [[UILabel alloc] initWithFrame:CGRectMake(210, 45, 100, 35)];
    [visitdateLabel setBackgroundColor:[UIColor clearColor]];
    [visitdateLabel setText:[NSString stringWithFormat:@"计划拜访时间：%@",visitor.visitDate]];
    [visitdateLabel setTextColor:[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1.0]];
    visitdateLabel.font=[UIFont systemFontOfSize:12];
    visitdateLabel.numberOfLines=2;
    [cell addSubview:visitdateLabel];
    
    UIImage* seletedImg = [UIImage imageNamed:@"tableviewcellSelected.png"];    
    UIImageView *seletedImgView =[[UIImageView alloc] initWithImage:seletedImg];
    [cell setSelectedBackgroundView:seletedImgView];
    
    
    UIImage* backImg = [UIImage imageNamed:@"tableviewcell.png"];    
    UIImageView *backImgView =[[UIImageView alloc] initWithImage:backImg];
    [cell setBackgroundView:backImgView];
    

    
    return cell;
    
}

//row高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 20;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
     
    return @"";
}


-(void) tableCellBeenPress:(int) index {
    simShopDetailController* shopController = [[simShopDetailController alloc] init];
    [shopController setDetailDelegate:self];
    [shopController setCustomerItem:[self.todayVisitorItemArray objectAtIndex:index]];
    [self.navigationController pushViewController:shopController animated:YES]; 
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self tableCellBeenPress:indexPath.row];
}


- (void)setdefaultFrame {
    if ([self.calendar isHidden] == YES) {
        return;
    }
    self.calendar.frame = CGRectMake(0, -self.calendar.frame.size.height+calendarShadowOffset, self.calendar.frame.size.width, self.calendar.frame.size.height);		
    [self.shopTableView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 
                                            self.view.bounds.size.height)];
}



- (void)weekView:(MAWeekView *)weekView eventTapped:(MAEvent *)event {
    
}

- (void)weekView:(MAWeekView *)weekView weekDidChange:(NSDate *)week {
    
    NSArray* weekArray = [self.weekcalendar.weekdayView weekdays];
    
    int i = 0;
    for (NSDate *date in weekArray) {
		NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
 
        UIButton* tempButton = [self.weekButtonArray objectAtIndex:i];
        
        NSString* tempBtTitle = [NSString stringWithFormat:@"%i",[components day]];
        [tempButton setTitle:tempBtTitle forState:UIControlStateNormal];
        [tempButton setSelected:NO];
       
        //加点
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd 00:00:00 +0000"]; 
        NSString *datestr=[dateFormatter stringFromDate:date];
        if([self.markArray containsObject:datestr]){
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFocDot.png"] forState:UIControlStateNormal];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFocselectedDot.png"] forState:UIControlStateSelected];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFocselectedDot.png"] forState:UIControlStateHighlighted];
        }else {
            [tempButton setBackgroundImage:nil forState:UIControlStateNormal];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFoc.png"] forState:UIControlStateSelected];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFoc.png"] forState:UIControlStateHighlighted];
        }
        
        i++;
    }   
}

- (void)weekView:(MAWeekView *)weekView eventDragged:(MAEvent *)event {
    
}

- (BOOL)weekView:(MAWeekView *)weekView eventDraggingEnabled:(MAEvent *)event {
    return NO;
}


- (void) weekButtonSelected:(UIButton*) bt {

    for (UIButton* bt in self.weekButtonArray) {
        [bt setSelected:NO];
    }
    
    [bt setSelected:YES];
    
    //设置数据
    NSArray* weekArray = [self.weekcalendar.weekdayView weekdays];
    NSDate *date = [weekArray objectAtIndex:bt.tag];
    
    NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:date];
    
    //NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setDateFormat:@"yyyy-MM-dd"]; // 这里是用大写的 H
    //dateStr = [dateFormatter stringFromDate:d];
    //2012-07-26
    
    NSString* year = [NSString stringWithFormat:@"%i",[components year]];
    
    NSString* month;
    if ([components month]<10) {
        month = [NSString stringWithFormat:@"0%i",[components month]];        
    }else {
        month = [NSString stringWithFormat:@"%i",[components month]];
    }

    NSString* day;
    if ([components day]<10) {
        day = [NSString stringWithFormat:@"0%i",[components day]];        
    }else {
        day = [NSString stringWithFormat:@"%i",[components day]];
    }
    
    self.dateStr = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    
    self.selectDay = self.dateStr;
    
    [self.todayVisitorItemArray removeAllObjects];
    
    for (visitorItem* item in self.visitorItemArray) {
        
        if ([item.visitDate isEqualToString: self.dateStr] == YES) {
            [self.todayVisitorItemArray addObject:item]; 
        }
    }
    
    [self.shopTableView reloadData];
}


- (void)requestFinished:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    
    //更新前，删除以前的所有数据
    [self.visitorItemArray removeAllObjects];

    
    if (!error) {
        NSString *response = [request responseString];
        NSLog(@"load data is :%@",response);
        NSDictionary* dict = [response objectFromJSONString];
        NSArray * dictArray=[dict objectForKey:@"siemensCustomer"];
        if(dictArray!=nil){
            NSMutableArray *marks = [[NSMutableArray alloc] init];
            for(int i=0;i<dictArray.count;i++){
                NSDictionary* temp = [dictArray objectAtIndex:i];
                visitorItem *d=[[visitorItem alloc] init];
                NSString *date=[temp objectForKey:@"planVisitDate"];
                d.visitDate=[date substringToIndex:10];
                [marks addObject:[NSString stringWithFormat:@"%@ 00:00:00 +0000",d.visitDate]];
                NSLog(@"visit date is %@",d.visitDate);
                d.visitNum=[temp objectForKey:@"visitNum"];
                d.visitedNum=[temp objectForKey:@"visitedNum"];
                d.contactName=[temp objectForKey:@"corporateDeputy"];
                if([[temp objectForKey:@"custPhone"] isKindOfClass:[NSString class]]==NO){
                    d.contactPhone=[[temp objectForKey:@"custPhone"] stringValue];
                }else {
                    d.contactPhone=[temp objectForKey:@"custPhone"];
                }
                d.custId=[temp objectForKey:@"custDetailId"];
                d.datelineId=[temp objectForKey:@"datelineId"];
                d.custNameEn=[temp objectForKey:@"custNameEn"];
                [self.visitorItemArray addObject:d];
            }
            self.markArray=[NSArray arrayWithArray:marks];
        }
        
       // self.todayVisitorItemArray = [[NSMutableArray alloc] initWithArray:self.visitorItemArray];
       NSString * sdate=@"";
        if (self.selectDay == nil || [self.selectDay isEqualToString:@""]) {
            NSDate* date = [NSDate date];
            NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            sdate = [formatter stringFromDate:date];
        }else {
            sdate=self.selectDay;
        }
        [self.todayVisitorItemArray removeAllObjects];
        
        for (visitorItem* item in self.visitorItemArray) {
            
            if ([item.visitDate isEqualToString: sdate] == YES) {
                [self.todayVisitorItemArray addObject:item]; 
            }
        }
        
    }
    
    [self hideMbProgress];
    [self.calendar reload];
    if (self.selectDay!=nil && ![self.selectDay isEqualToString:@""]) {
        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        [self.calendar selectDate:[formatter dateFromString:self.selectDay]];
    }
    
   [self.shopTableView reloadData];
    
    //刷新周的点
    NSArray* weekArray = [self.weekcalendar.weekdayView weekdays];
    
    int i = 0;
    for (NSDate *date in weekArray) {
		UIButton* tempButton = [self.weekButtonArray objectAtIndex:i];
        //加点
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd 00:00:00 +0000"]; 
        NSString *datestr=[dateFormatter stringFromDate:date];
        if([self.markArray containsObject:datestr]){
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFocDot.png"] forState:UIControlStateNormal];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFocselectedDot.png"] forState:UIControlStateSelected];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFocselectedDot.png"] forState:UIControlStateHighlighted];
        }else {
            [tempButton setBackgroundImage:nil forState:UIControlStateNormal];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFoc.png"] forState:UIControlStateSelected];
            [tempButton setBackgroundImage:[UIImage imageNamed:@"weekbtFoc.png"] forState:UIControlStateHighlighted];
        }
        
        i++;
    }   

}


- (void)requestFailed:(ASIHTTPRequest *)request {
    [self hideMbProgress];
}


-(void) updateFromHttp :(NSString*) startDate endDate:(NSString*) endDate {
    //临时方案，更新3个月的数据。前后，各1个月
    
    NSArray* startArray = [startDate componentsSeparatedByString:@"-"];
    NSArray* endArray = [endDate componentsSeparatedByString:@"-"];
    
    int startYear = [[startArray objectAtIndex:0] intValue];
    int startMonth = [[startArray objectAtIndex:1] intValue];
//    int startDay = [[startArray objectAtIndex:2] intValue];
    
    int endYear = [[endArray objectAtIndex:0] intValue];
    int endMonth = [[endArray objectAtIndex:1] intValue];
    //    int startDay = [[startArray objectAtIndex:2] intValue];

    //前后各加1个月
    if (startMonth == 1) {
        startYear--;
        startMonth = 12;
    }else {
        startMonth--;
    }

    if (endMonth == 12) {
        endYear++;
        endMonth = 1;
    }else {
        endMonth++;
    }
    
    NSString* startMonthStr;
    if (startMonth < 10) {
        startMonthStr = [NSString stringWithFormat:@"0%i",startMonth];        
    }else {
        startMonthStr = [NSString stringWithFormat:@"%i",startMonth];
    }
    
    NSString* endMonthStr;
    if (endMonth < 10) {
        endMonthStr = [NSString stringWithFormat:@"0%i",endMonth];        
    }else {
        endMonthStr = [NSString stringWithFormat:@"%i",endMonth];
    }
    
    NSString* startDt = [NSString stringWithFormat:@"%d-%@-23",startYear,startMonthStr];
    NSString* endDt = [NSString stringWithFormat:@"%d-%@-06",endYear,endMonthStr];
    
    
    ////////////
    
    NSString *u=[NSString stringWithFormat:@"%@/getVisitSiemensCustomers?startDay=%@&endDay=%@&mobile=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],startDt,endDt,[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
    NSLog(@"request for url:%@",u);
    NSURL *url = [NSURL URLWithString:u];
    self.request = [ASIHTTPRequest requestWithURL:url];
    [self.request setDelegate:self];
    [self.request start];
    
    [self showMbprogress];
}


-(void) updateFromHttp {
    
    
    
    NSDate* date = [NSDate date];
    
    
    //如果month已经被切换，比如，换到了12月，修改后，更新12月的数据
    if (self.calendar) {
        if (self.calendar.dateSelected) {
            date = self.calendar.dateSelected;
        }
    }
    
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-"];
    NSString* dateStr = [formatter stringFromDate:date];
    
    NSString* startDate = [NSString stringWithFormat:@"%@01",dateStr];
    NSString* endDate = [NSString stringWithFormat:@"%@31",dateStr];
    
    [self updateFromHttp: startDate endDate: endDate];
    
//    NSString *u=[NSString stringWithFormat:@"%@/getVisitSiemensCustomers?startDay=%@&endDay=%@&mobile=%@&pwd=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"WebserviceUrl"],@"2012-07-01",@"2012-08-30",[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginMobile"],[[NSUserDefaults standardUserDefaults]objectForKey:@"LoginPassword"]];
//    
//    NSURL *url = [NSURL URLWithString:u];
//    self.request = [ASIHTTPRequest requestWithURL:url];
//    [self.request setDelegate:self];
//    [self.request start];
//
//    [self showMbprogress];
}


- (void)SubmitVisitSuccess{
    [self updateFromHttp];
}
@end
